package com.tushen.labor.data;

import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.tushen.labor.bean.Weather;
import com.tushen.labor.bean.WeatherInfo;
import com.tushen.labor.util.DateUtil;

import java.net.InetAddress;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.hutool.http.HttpUtil;

public class DataUtil {

    private static final String TAG = "DataUtil";

    private static final String key_weather = "a39d969891cf0f04e3d0df283f0b79b6";

    private static final String key_ip = "dd0c73354f9027007527051e548f0734";

    private static String getIp(){
        String ip = "";
        String url = "https://www.taobao.com/help/getip.php";
        try{
            String jsonStr = HttpUtil.get(url);
            Log.d(TAG, "getIp: " + jsonStr);
            if (jsonStr != null && !"".equals(jsonStr)){
                String ipstr = jsonStr.substring(jsonStr.indexOf("(")+1,jsonStr.indexOf(")"));
                ip = JSON.parseObject(ipstr).getString("ip");
            }
            //Log.d(TAG, "getIp: " + ip);
        } catch (Exception e){
            Log.e(TAG, "getIp: " + e.getMessage());
            e.printStackTrace();
        }

        return ip;
    }

    private static String[] getCityIP() {
        String[] returnStr = new String[2];
        String ip = "";
        String city = "";
        String url = "https://myip.ipip.net/";
        try{
            String jsonStr = HttpUtil.get(url);
            Log.d(TAG, "getCityIP: " + jsonStr);
            if (jsonStr != null && !"".equals(jsonStr)){
                if (jsonStr.contains("IP：")){
                    ip = jsonStr.substring(jsonStr.indexOf("：")+1,jsonStr.indexOf("来自")).trim();
                    city =  jsonStr.substring(jsonStr.indexOf("来自于：")).split(" ")[2];
                }
            }
        } catch (Exception e){
            Log.e(TAG, "getCityIP: " + e.getMessage());
            e.printStackTrace();
        } finally {
            returnStr[0] = ip;
            returnStr[1] = city;
        }
        return returnStr;
    }

    private static String getCity(String ip){
        String city = "";
        String url = "http://apis.juhe.cn/ip/ipNewV3";

        Map<String, Object> params = new HashMap<>();
        params.put("ip", ip);
        params.put("key", key_ip);
        try{
            String jsonStr = HttpUtil.get(url, params);
            Log.d(TAG, "getCity: " + jsonStr);
            if (jsonStr != null && !"".equals(jsonStr)){
                JSONObject jsonObject = JSON.parseObject(jsonStr);
                int error_code = jsonObject.getInteger("error_code");
                if (error_code == 0) {
                    JSONObject result = jsonObject.getJSONObject("result");
                    city = result.getString("City");
                }
            }
            //Log.d(TAG, "getCity: " + city);
        }catch (Exception e){
            Log.e(TAG, "getCity: " + e.getMessage() );
            e.printStackTrace();
        }

        return city;
    }

    public static List<WeatherInfo> getWeatherInfo() {
        try {
            List<WeatherInfo> retList = new ArrayList<>();
            String[] cityip = getCityIP();
            String city = cityip[1];
            String ip = cityip[0];
            if ("".equals(city)){
                if ("".equals(ip)){
                   ip = getIp();
                }
                city = getCity(ip);
            }

            String url = "http://apis.juhe.cn/simpleWeather/query";

            Map<String, Object> params = new HashMap<>();//组合参数
            params.put("city", city);
            params.put("key", key_weather);

            String returnStr = HttpUtil.get(url,params);
            //String returnStr = "{\"reason\":\"查询成功!\",\"result\":{\"city\":\"武汉\",\"realtime\":{\"temperature\":\"32\",\"humidity\":\"62\",\"info\":\"阴\",\"wid\":\"02\",\"direct\":\"西风\",\"power\":\"4级\",\"aqi\":\"31\"},\"future\":[{\"date\":\"2023-06-29\",\"temperature\":\"25\\/32℃\",\"weather\":\"中雨转暴雨\",\"wid\":{\"day\":\"08\",\"night\":\"10\"},\"direct\":\"西南风转持续无风向\"},{\"date\":\"2023-06-30\",\"temperature\":\"25\\/30℃\",\"weather\":\"小雨转多云\",\"wid\":{\"day\":\"07\",\"night\":\"01\"},\"direct\":\"西南风\"},{\"date\":\"2023-07-01\",\"temperature\":\"26\\/33℃\",\"weather\":\"阵雨转多云\",\"wid\":{\"day\":\"03\",\"night\":\"01\"},\"direct\":\"西南风\"},{\"date\":\"2023-07-02\",\"temperature\":\"29\\/33℃\",\"weather\":\"多云\",\"wid\":{\"day\":\"01\",\"night\":\"01\"},\"direct\":\"西南风\"},{\"date\":\"2023-07-03\",\"temperature\":\"28\\/33℃\",\"weather\":\"阴转小雨\",\"wid\":{\"day\":\"02\",\"night\":\"07\"},\"direct\":\"西南风\"}]},\"error_code\":0}";
            Log.d(TAG, "getWeatherInfo: " + returnStr);
            try {
                JSONObject jsonObject = JSON.parseObject(returnStr);
                int error_code = jsonObject.getInteger("error_code");
                if (error_code == 0) {
                    JSONObject result = jsonObject.getJSONObject("result");
                    JSONObject realtime = result.getJSONObject("realtime");

                    String hour = DateUtil.getNowHHStr();
                    Integer houtInt = Integer.parseInt(hour);

                    JSONArray jsonArray = result.getJSONArray("future");
                    JSONObject jsonObject0 = jsonArray.getJSONObject(0);
                    JSONObject jsonWid0 = jsonObject0.getJSONObject("wid");
                    String widHour0 = houtInt >= 18 ? jsonWid0.getString("night") : jsonWid0.getString("day");
                    WeatherInfo w1 = new WeatherInfo();
                    w1.setWeather(Weather.matchCode(widHour0));
                    w1.setDateStr(jsonObject0.getString("date"));
                    w1.setWeekStr(DateUtil.getNowWeekOfDate());
                    w1.setCurrTemperature(realtime.getString("temperature"));
                    w1.setTemperatureRange(jsonObject0.getString("temperature"));
                    w1.setWindDescription(jsonObject0.getString("direct"));
                    retList.add(w1);

                    JSONObject jsonObject1 = jsonArray.getJSONObject(1);
                    JSONObject jsonWid1 = jsonObject1.getJSONObject("wid");
                    String widHour1 = houtInt >= 18 ? jsonWid1.getString("night") : jsonWid1.getString("day");
                    WeatherInfo w2 = new WeatherInfo();
                    w2.setWeather(Weather.matchCode(widHour1));
                    w2.setDateStr(jsonObject1.getString("date"));
                    w2.setWeekStr(DateUtil.getWeekOfDate(1));
                    w2.setTemperatureRange(jsonObject1.getString("temperature"));
                    w2.setWindDescription(jsonObject1.getString("direct"));
                    retList.add(w2);

                    JSONObject jsonObject2 = jsonArray.getJSONObject(2);
                    JSONObject jsonWid2 = jsonObject2.getJSONObject("wid");
                    String widHour2 = houtInt >= 18 ? jsonWid2.getString("night") : jsonWid1.getString("day");
                    WeatherInfo w3 = new WeatherInfo();
                    w3.setWeather(Weather.matchCode(widHour2));
                    w3.setDateStr(jsonObject2.getString("date"));
                    w3.setWeekStr(DateUtil.getWeekOfDate(2));
                    w3.setTemperatureRange(jsonObject2.getString("temperature"));
                    w3.setWindDescription(jsonObject2.getString("direct"));
                    retList.add(w3);

                } else {
                    Log.d(TAG, "getWeatherInfo: 调用接口失败：" + jsonObject.getString("reason"));
                }
            } catch (Exception e) {
                Log.e(TAG, "getWeatherInfo: " + e.getMessage());
                e.printStackTrace();
            }

            return retList;

        } catch (Exception e) {
            Log.e(TAG, "getWeatherInfo: " + e.getMessage());
            e.printStackTrace();
            return null;
        }
    }

}
